package com.bpz.utils;

import org.apache.log4j.Logger;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;

public class SessionUtils {
	static Logger logger = Logger.getLogger(SessionUtils.class);
	private static SessionUtils single = null;

	// 静态工厂方法
	public synchronized static SessionUtils getInstance() {
		if (single == null) {
			single = new SessionUtils();
		}
		return single;
	}

	/**
	 * 设置session值
	 * 
	 * @param sessionKey
	 *            名称
	 * @param value
	 *            值
	 * @param request
	 *            HttpServletRequest
	 */
	public void set(String sessionKey, Object value) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes()).getRequest();
		HttpSession session = request.getSession();
		session.removeAttribute(sessionKey);
		session.setAttribute(sessionKey, value);
	}

	/**
	 * 删除指定的session
	 * 
	 * @param sessionKey
	 */
	public void remove(String sessionKey) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes()).getRequest();
		HttpSession session = request.getSession();
		session.removeAttribute(sessionKey);
	}

	/**
	 * 删除所有session
	 */
	public void removeAll() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes()).getRequest();
		HttpSession session = request.getSession();
		Enumeration<String> enumeration = session.getAttributeNames();
		while (enumeration.hasMoreElements()) {
			String name = (String) enumeration.nextElement();
			session.removeAttribute(name);
			logger.info("Session名称"+name);
		}
	}

	/**
	 * 设置session值
	 * 
	 * @param sessionKey
	 *            名称
	 * @param value
	 *            值
	 * @param interval
	 *            session失效时间(单位分钟)
	 * @param request
	 *            HttpServletRequest
	 */
	public void set(String sessionKey, Object value, Integer interval) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes()).getRequest();
		HttpSession session = request.getSession();
		session.setMaxInactiveInterval(interval);
		session.removeAttribute(sessionKey);
		session.setAttribute(sessionKey, value);
	}

	/**
	 * 获取指定名称的session值
	 * 
	 * @param sessionKey
	 * @param request
	 * @return
	 */
	public Object get(String sessionKey) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes()).getRequest();
		HttpSession session = request.getSession();
		Object value = session.getAttribute(sessionKey);
		return value;
	}
}
